import MD5 from 'md5'
// 避免短时间内点击多次
export const throttle = function (fn, gapTime) {
  if (gapTime == null || gapTime === undefined) {
    gapTime = 300
  }

  let _lastTime = null

  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) // 将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}
// 时间戳转日期
export default function dateFormat(date, fmt = 'yyyy/MM/dd') {
  if (!(date instanceof Date)) {
    date = new Date(date)
  }
  var o = {
    'M+': date.getMonth() + 1, // 月份o
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return fmt
}

// json 整型
export function jsonInteger(oldJson) {
  oldJson.rnd = randomString()
  oldJson.timestamp = timeStamp()
  // 并且将获取cookie的时间戳
  let signature = getSignature(oldJson)
  oldJson.signature = signature
  return oldJson
}
// 获取报名的signature
export function jsonFreeInteger(oldJson) {
  oldJson.rnd = randomString()
  oldJson.timestamp = timeStamp()
  let keyArray = []
  for (var key in oldJson) {
    keyArray.push(key.trim())
  }
  keyArray.forEach(function (keyItem) {
    if (typeof oldJson[keyItem] === 'string') {
      oldJson[keyItem] = oldJson[keyItem].trim() // 内容去空格
    }
  })
  // 并且将获取cookie的时间戳
  let signature = getFreeSignature(oldJson)
  oldJson.signature = signature.trim()
  return oldJson
}
// 获取报名的signature
function getFreeSignature(params) {
  let keyArray = []
  for (var key in params) {
    keyArray.push(key.trim())
  }
  // 将键值组成的数组排序
  keyArray.sort((a, b) => a.localeCompare(b))
  let signature = ''
  keyArray.forEach(function (keyItem) {
    signature += keyItem.trim() + '=' + params[keyItem] + '&'
  })
  let NewSignature = ''
  NewSignature =
    signature.substr(0, signature.length - 1).trim() +
    '6tu8wkKpxCCmzKHXG7eSjky2yBmlhcQU'
  return MD5(NewSignature.trim())
}
// 获取视频的signature
export function jsonVideoInteger(oldJson) {
  oldJson.rnd = randomString()
  oldJson.timestamp = timeStamp()
  // 并且将获取cookie的时间戳
  let signature = getVideoSignature(oldJson)
  oldJson.signature = signature.trim()
  return oldJson
}
// 获取视频的signature
function getVideoSignature(params) {
  let keyArray = []
  for (var key in params) {
    keyArray.push(key.trim())
  }
  // 将键值组成的数组排序
  keyArray.sort((a, b) => a.localeCompare(b))
  let signature = ''
  keyArray.forEach(function (keyItem) {
    signature += keyItem.trim() + '=' + params[keyItem] + '&'
  })
  let NewSignature = ''
  NewSignature =
    signature.substr(0, signature.length - 1).trim() +
    'lwJI6lbehhhQLZWOLbEgqcdxuGpyi4WZ'
  return MD5(NewSignature.trim())
}
// 获取10位随机字符串
export function randomString() {
  let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  var maxPos = chars.length
  var pwd = ''
  for (var i = 0; i < 8; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

// 获取 signature
export function getSignature(params) {
  let keyArray = []
  for (var key in params) {
    keyArray.push(key)
  }
  // 将键值组成的数组排序
  keyArray.sort((a, b) => a.localeCompare(b))
  let signature = ''
  keyArray.forEach(function (keyItem) {
    signature += keyItem + '=' + params[keyItem] + '&'
  })
  // 秘钥拼接
  const NewSignature =
    'V0j7lEImJmCQTr7xEfPUhr7yfveJeSMI' +
    signature.substr(0, signature.length - 1) +
    'V0j7lEImJmCQTr7xEfPUhr7yfveJeSMI'
  return MD5(NewSignature)
}

// 获取时间戳
export function timeStamp() {
  let ts = Math.round(new Date().getTime() / 1000)
  return ts
}

export function getQuery(name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  const r =
    window.location.search.substr(1).match(reg) ||
    window.location.hash
      .substring(window.location.hash.search(/\?/) + 1)
      .match(reg)
  if (r != null) {
    return decodeURIComponent(r[2])
  } else {
    return null
  }
}

// 删除地址栏参数的方法 //url:网页地址|ref:想删除的参数名
export const removeQuery = (paramKey, url) => {
  // var url = window.location.href;    //页面url
  var urlParam = window.location.search.substr(1) // 页面参数
  var beforeUrl = url.substr(0, url.indexOf('?')) // 页面主地址（参数之前地址）
  var nextUrl = ''

  var arr = new Array()
  if (urlParam !== '') {
    var urlParamArr = urlParam.split('&') // 将参数按照&符分成数组
    for (var i = 0; i < urlParamArr.length; i++) {
      var paramArr = urlParamArr[i].split('=') // 将参数键，值拆开
      // 如果键雨要删除的不一致，则加入到参数中
      if (paramArr[0] !== paramKey) {
        arr.push(urlParamArr[i])
      }
    }
  }
  if (arr.length > 0) {
    nextUrl = '?' + arr.join('&')
  }
  url = beforeUrl + nextUrl
  return url
}
